<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容"
            v-model="userinfo.query"
            @input="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
            ></el-button> </el-input
        ></el-col>
        <!-- 按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userlist" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽，渲染开关 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="changStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="" label="操作" width="180px">
          <!-- 作用域插槽，渲染操作按钮 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditForm(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配用户"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRoles(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUsers(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="dialogVisible"
        width="50%"
        @close="closeDialog"
      >
        <!-- 主题内容 -->
        <span>
          <el-form :model="addForm" :rules="addFormrules" ref="addForm">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <!-- 按钮 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="verifyForm">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="isEditForm"
        width="50%"
        @close="closeEditForm"
      >
        <span>
          <el-form :model="editForm" :rules="editFormRules" ref="editForm">
            <el-form-item label="用户名">
              <el-input v-model="editForm.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer">
          <el-button @click="isEditForm = false">取 消</el-button>
          <el-button type="primary" @click="editFormData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配权限框 -->
      <el-dialog title="分配角色" :visible.sync="isUserRoledialog" width="50%"  @close="clearHisRole">
        <div class="rolesMof">
          <p>用户名：{{ usermess.username }}</p>
          <p>角色名：{{ usermess.role_name }}</p>
          <el-select v-model="rolesId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="isUserRoledialog = false">取 消</el-button>
          <el-button type="primary" @click="setRoles"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    //自定义验证邮箱
    let checkEmail = (rule, value, cb) => {
      let emailRule = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (emailRule.test(value)) {
        cb();
      } else {
        cb(new Error("请输入正确的邮箱"));
      }
    };
    //自定义验证手机
    let checkmobile = (rule, value, cb) => {
      let mobileRule = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/;
      if (mobileRule.test(value)) {
        cb();
      } else {
        cb(new Error("请输入正确的手机号码"));
      }
    };
    return {
      userinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      userlist: [],
      total: 0,
      dialogVisible: false,
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      //验证添加用户表单
      addFormrules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 5,
            max: 15,
            message: "长度在 5 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkmobile, trigger: "blur" },
        ],
      },
      isEditForm: false,
      editForm: {},
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: checkmobile, trigger: "blur" },
        ],
      },
      isUserRoledialog: false,
      usermess: {},
      rolesId: '',
      rolesList: []
    };
  },
  methods: {
    //获取用户列表
    async getUserList() {
      let { data: res } = await this.$http.get("users", {
        params: this.userinfo,
      });
      console.log(res);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    //显示页数
    handleSizeChange(val) {
      //console.log(val)
      this.userinfo.pagesize = val;
      this.getUserList();
    },
    //当前页码
    handleCurrentChange(val) {
      //console.log(val)
      this.userinfo.pagenum = val;
      this.getUserList();
    },
    //监听插槽，改变用户状态
    async changStatus(state) {
      //console.log(state)
      let { data: res } = await this.$http.put(
        `users/${state.id}/state/${state.mg_state}`
      );
      console.log(res);
      if (res.meta.status != 200) {
        state.mg_state = !state.mg_state;
        return this.$message.error("更新失败");
      }
      this.$message.success("更新状态成功");
    },
    //重置添加用户表单
    closeDialog() {
      this.$refs.addForm.resetFields();
    },
    //验证添加用户表单
    verifyForm() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$http.post("users", this.addForm);
        if (res.meta.status != 201) return this.$message.error("添加失败");
        this.$message.success("添加成功");
        this.dialogVisible = false;
        this.getUserList();
      });
    },
    //显示隐藏编辑用户，获取编辑信息
    async showEditForm(id) {
      this.isEditForm = true;
      console.log(id);
      let { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      this.editForm = res.data;
    },
    //重置编辑用户表单
    closeEditForm() {
      this.$refs.editForm.resetFields();
    },
    //更新编辑用户表单
    editFormData() {
      this.$refs.editForm.validate(async (vaild) => {
        if (!vaild) return;
        let { data: res } = await this.$http.put("users/" + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile,
        });
        console.log(res);
        if (res.meta.status != 200) return this.$message.error("更新用户失败");
        this.isEditForm = false;
        this.getUserList();
        this.$message.success("更新用户信息成功");
      });
    },
    //删除用户，用到$confirm方法
    removeUsers(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .catch((err) => err)
        .then(async (confirm) => {
          if (confirm !== "confirm") {
            return this.$message.info("取消删除成功");
          }
          console.log(confirm);
          let { data: res } = await this.$http.delete("users/" + id);
          if (res.meta.status != 200) return this.$message.error("删除失败");
          this.$message.success("删除成功");
          this.getUserList();
        });
    },
    //获取用户角色列表
    async showRoles(role) {
      this.usermess = role;
      this.isUserRoledialog = true;
      let {data:res} = await this.$http.get("roles")
      console.log(res)
      this.rolesList = res.data
    },
    //分配角色
    async setRoles(){
      let {data:res} = await this.$http.put(`users/${this.usermess.id}/role`
      ,{rid: this.rolesId})
      if(res.meta.status !=200) return this.$message.error("分配角色失败")
      this.$message.success("分配角色成功")
      this.getUserList()
      this.isUserRoledialog = false
    },
    //监听分配角色，关闭后重置选项
    clearHisRole(){
      this.rolesId = ''
      this.usermess = {}
    }
  },
  created() {
    this.getUserList();
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  font-size: 12px;
}
.el-table {
  margin-top: 20px;
  font-size: 13px;
}

/deep/ .el-dialog__body {
  padding: 10px;

  .rolesMof {
    text-align: left;
    .el-input{
      margin-top: 5px;
    }
    p {
      padding: 5px 0;
    }
  }
}

</style>